package com.example.utils;

import com.example.model.DrugModel;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.*;
import org.springframework.util.ResourceUtils;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 业务聚合
 *
 * @version [V2.0]
 * @package com.example.utils;
 * @description:[用一句话描述该文件做什么]
 * @author: [zhuben]
 * @date: [2024-02-01 14:03]
 * @copyright: 2024 echovin.com
 */

public class LuceneUtils {
    public static void createIndies(List<DrugModel> drugModels){
        Analyzer analyzer = new StandardAnalyzer();
        IndexWriterConfig indexWriterConfig = null;
        Directory directory = null;
        IndexWriter indexWriter = null;
        String lock = null;
        try {
            indexWriterConfig = new IndexWriterConfig(analyzer);
            File fileIndex = ResourceUtils.getFile("/drug");
            directory = FSDirectory.open(Paths.get(fileIndex.toURI()));
            indexWriter = new IndexWriter(directory, indexWriterConfig);
            //全量删除
            indexWriter.deleteAll();
            indexWriter.flush();
            indexWriter.commit();
            //全量插入
            List<Document> documents = new ArrayList<>();
            for (DrugModel drugModel : drugModels){
                Document document = new Document();
                document.add(new org.apache.lucene.document.StringField("id", drugModel.getId().toString(), Field.Store.YES));
                document.add(new org.apache.lucene.document.TextField("drugName", drugModel.getDurgName(), Field.Store.YES));
                documents.add(document);
            }

            if (documents != null &&documents.size() > 0){
                indexWriter.addDocuments(documents);
                indexWriter.flush();
                indexWriter.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (indexWriter != null){
                    indexWriter.close();
                }
                if (directory != null){
                    directory.close();
                }
            } catch (Exception e) {
            }
        }
    }

    public static void deleteIndex(String id){
        IndexWriter indexWriter = null;
        Directory directory = null;
        IndexWriterConfig indexWriterConfig = null;
        String lock = null;
        try {
            Analyzer analyzer = new IKAnalyzer();
            indexWriterConfig = new IndexWriterConfig(analyzer);
            File fileIndex = ResourceUtils.getFile("/drug");
            directory = FSDirectory.open(Paths.get(fileIndex.toURI()));
            indexWriter = new IndexWriter(directory, indexWriterConfig);
            indexWriter.deleteDocuments(new Term("id", id));
            indexWriter.flush();
            indexWriter.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (indexWriter != null){
                    indexWriter.close();
                }
                if (directory != null){
                    directory.close();
                }
            } catch (Exception e) {
            }
        }
    }

    public static void updateOrAddIndex(List<DrugModel> drugModels){
        IndexWriter indexWriter = null;
        IndexReader indexReader = null;
        Directory directory = null;
        IndexWriterConfig indexWriterConfig = null;
        String lock = null;
        try {
            Analyzer analyzer = new StandardAnalyzer();
            indexWriterConfig = new IndexWriterConfig(analyzer);
            File fileIndex = ResourceUtils.getFile("/drug");
            directory = FSDirectory.open(Paths.get(fileIndex.toURI()));

            indexReader = DirectoryReader.open(directory);
            IndexSearcher indexSearcher = new IndexSearcher(indexReader);
            indexWriter = new IndexWriter(directory, indexWriterConfig);

            List<Document> documents = new ArrayList<>();
            for (DrugModel drugModel : drugModels){
                Document document = new Document();
                document.add(new org.apache.lucene.document.StringField("id", drugModel.getId().toString(), Field.Store.YES));
                document.add(new org.apache.lucene.document.StringField("drugName", drugModel.getDurgName(), Field.Store.YES));
                documents.add(document);
            }
            for (Document document : documents){
                String pkId = document.get("id");
                int count = indexSearcher.count(new TermQuery(new Term("id", pkId)));
                if (count > 0){
                    //更新
                    indexWriter.updateDocument(new Term("id", pkId), document);
                }else{
                    //新增
                    indexWriter.addDocument(document);
                }
            }

            indexWriter.flush();
            indexWriter.commit();
        } catch (Exception e) {
            try {
                if (indexWriter != null){
                    indexWriter.rollback();
                }
            } catch (Exception ex) {
            }
        } finally {
            try {
                if (indexWriter != null){
                    indexWriter.close();
                }
                if (indexReader != null){
                    indexReader.close();
                }
                if (directory != null){
                    directory.close();
                }
            } catch (Exception e) {
            }
        }
    }


    public static List<Document> searchPage(IndexSearcher indexSearcher, Query query, int pageIndex, int pageSize) throws Exception {
        List<Document> documents = new ArrayList<>();
        try {
            ScoreDoc after = null;
            if (pageIndex > 0){
                TopDocs topDocs = indexSearcher.searchAfter(null, query, pageSize*pageIndex);
                if (topDocs.scoreDocs.length>=1){
                    after = topDocs.scoreDocs[topDocs.scoreDocs.length-1];
                }
            }
            TopDocs topDocs1 = indexSearcher.searchAfter(after, query, pageSize);
            System.out.println("医嘱开立检索:"+query.toString()+",命中数:"+topDocs1.totalHits);
            ScoreDoc[] scoreDocs = topDocs1.scoreDocs;
            for (ScoreDoc scoreDoc : scoreDocs) {
                int docId = scoreDoc.doc;
                float score = scoreDoc.score;
                if (score <= 0.0d) {
                    continue;
                }
                Document document = indexSearcher.doc(docId);
                documents.add(document);
            }
            return documents;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    public static IndexSearcher indexSearcher() throws Exception {
        try {
            File file = ResourceUtils.getFile("/drug");
            Directory directory = MMapDirectory.open(Paths.get(file.toURI()));
            DirectoryReader indexReader = DirectoryReader.open(directory);
            return new IndexSearcher(indexReader);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
